<template>
  <div>
    <QueryForm
      v-model="filters"
      :show-qk="showQk"
      :query-form-config="queryFormConfig"
      @handleQuery="getDataList(1)"
    >
      <template v-if="meta.indexOf('MemberConsumptionExport') > -1" #btns>
        <el-button v-preventReClick type="primary" @click="exportExcel">{{ $t('message.daochu') }}</el-button>
      </template>
    </QueryForm>
    <el-table
      ref="tableRef"
      :data="list"
      :span-method="objectSpanMethod"
      border
      show-summary
      :summary-method="getSummaries"
      fit
      :header-row-class-name="'table-header'"
      class="doumee-table"
    >
      <el-table-column
        prop="cardTypeName"
        :label="$t('message.hylx')"
        min-width="200"
        align="center"
      />
      <el-table-column
        prop="venueName"
        align="center"
        :label="$t('message.cg')"
        min-width="200"
      />
      <el-table-column
        prop="addNum"
        align="center"
        :label="$t('message.xzhy2')"
        min-width="200"
      />
      <el-table-column
        prop="addMoney"
        align="center"
        :label="$t('message.czje')"
        min-width="120"
      />
      <el-table-column :label="$t('message.hykxf')" align="center">
        <el-table-column
          prop="site"
          :label="$t('message.cd')"
          align="center"
          min-width="120"
        />
        <el-table-column
          prop="ticket"
          :label="$t('message.mp')"
          align="center"
          min-width="120"
        />
        <el-table-column
          prop="goods"
          :label="$t('message.sp')"
          align="center"
          min-width="120"
        />
        <el-table-column
          prop="diancan"
          :label="$t('message.dc')"
          align="center"
          min-width="120"
        />
        <el-table-column
          prop="meals"
          :label="$t('message.tc')"
          align="center"
          min-width="120"
        />
        <el-table-column
          prop="normal"
          :label="$t('message.tonyon')"
          align="center"
          min-width="120"
        />
        <el-table-column
          prop="course"
          :label="$t('message.kc')"
          align="center"
          min-width="120"
        />
        <el-table-column
          prop="activity"
          :label="$t('message.hd')"
          align="center"
          min-width="120"
        />
        <el-table-column
          prop="moment"
          :label="$t('message.jcsj')"
          align="center"
          min-width="120"
        />
        <el-table-column
          prop="lease"
          :label="$t('message.qczl')"
          align="center"
          min-width="120"
        />
        <el-table-column
          prop="escort"
          :label="$t('message.byk')"
          align="center"
          min-width="120"
        />
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import * as XLSX from 'xlsx/xlsx.mjs'
import XLSX_STYLE from 'xlsx-style'
import { saveAs } from 'file-saver'
import { parseTime } from '@/utils/index'
import { memberStatistics, cardList } from '@/api'
import { getFMdate } from '@/utils/index'
import { queryFormConfig } from './config'
export default {
  data() {
    return {
      queryFormConfig,
      showQk: false,
      cardList: [],
      list: [],
      mergeList: [],
      mergeIndexList: [],
      listLoading: true,
      pagination: {
        page: 1,
        rows: 10,
        firstQueryTime: new Date()
      },

      total: 0,
      dateIndex: 1,
      filters: {},
      meta: [],
      weekList: []
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.setDate(new Date())
    this.getVenueList()
    this.getCardList()
  },
  methods: {
    getDataList() {
      memberStatistics({
        param: {
          cardTypeId: this.filters.cardId,
          startTime: this.filters.time[0],
          endTime: this.filters.time[1],
          venueId: sessionStorage.getItem('venueId')
        }
      })
        .then((res) => {
          this.listLoading = false
          if (res.errorCode !== '000000') return
          const dataList = res.recordList
          const recordList = []
          const mergeList = []
          const mergeIndexList = []
          var colnum = 0
          var idx = 0
          dataList.forEach((e) => {
            colnum += e.responseList.length
            e.responseList.forEach((s) => {
              s['cardTypeName'] = e['cardTypeName']
              mergeList.push(colnum)
              recordList.push(s)
              mergeIndexList.push(idx)
            })
            idx += e.responseList.length
          })
          this.list = recordList
          this.mergeList = mergeList
          this.mergeIndexList = mergeIndexList
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    getCardList() {
      // 获取列表
      cardList({
        param: {
          type: '1'
        }}).then(res => {
        if (res.errorCode === '000000') {
          this.cardList = res.recordList
          const arr = res.recordList
          this.queryFormConfig.formItems[0].options = arr
        }
      }).catch(err => {
        console.log(err)
      })
    },

    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = this.$t('message.heji')
          return
        } else if (index === 1) {
          sums[index] = '-'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
        } else {
          sums[index] = '-'
        }
      })

      for (var key = 1; key <= sums.length; key++) {
        const number = sums[key]
        if (!isNaN(number)) {
          sums[key] = parseFloat(number).toFixed(2)
        }
      }
      return sums
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        var rowm = this.mergeList[rowIndex] - rowIndex
        var rowidx = this.mergeIndexList[rowIndex]
        if (rowIndex === rowidx) {
          return {
            rowspan: rowm,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      } else {
        return {
          rowspan: 1,
          colspan: 1
        }
      }
    },
    // 获取场馆列表
    getVenueList() {
      this.getDate(1)
      this.getDataList()
    },
    getDate(e) {
      this.dateIndex = e
      if (e === 1) {
        this.$set(this.filters, 'time', [getFMdate(-1, '-').slice(0, 10), getFMdate(-1, '-').slice(0, 10)])
      } else if (e === 2) {
        this.$set(this.filters, 'time', [this.weekList[0].value, this.weekList[6].value])
      } else {
        var date = new Date()
        var year = date.getFullYear() + '-'
        var month = this.calculation(date.getMonth() + 1) + '-'
        var day = new Date(date.getFullYear(), date.getMonth() + 1, 0)
        this.$set(this.filters, 'time', [year + month + '01', year + month + day.getDate()])
      }
      this.getDataList()
    },
    calculation(s) {
      return s < 10 ? '0' + s : s
    },
    formatDate(date) {
      const year = date.getFullYear() + '-'
      const month = this.calculation(date.getMonth() + 1) + '-'
      const day = this.calculation(date.getDate())
      const week = [this.$t('message.z7', this.$t('message.z1'), this.$t('message.z2'), this.$t('message.z3'), this.$t('message.z4'), this.$t('message.z5'), this.$t('message.z6'))][date.getDay()]
      return {
        label: month + day + ' ' + week,
        value: year + month + day,
        old: new Date(date)
      }
    },
    addDate(date, n) {
      date.setDate(date.getDate() + n)
      return date
    },
    setDate(date) {
      var week = date.getDay() - 1
      if (week === -1) {
        week = 6
      }
      date = this.addDate(date, week * -1)
      this.currentDate = new Date(date)
      const arr = []
      for (var i = 0; i < 7; i++) {
        arr[i] = this.formatDate(i === 0 ? date : this.addDate(date, 1))
      }
      this.weekList = arr
    },
    exportExcel() {
      const time = new Date().getTime()
      const filename = this.$t('message.hytjfx') + time + '.xlsx'
      const user = this.$store.state.app.user
      const param = this.filters
      var aoa = []
      if (param.time && param.time.length > 0) {
        aoa = [
          [this.$t('message.cxqsrq') + param.time[0] + ' 00:00:00' + this.$t('message.cxzjrq') + param.time[1] + ' 23:59:59']
        ]
      }
      const workbook = XLSX.utils.book_new()
      var bottom = [
        [this.$t('message.dcsj') + parseTime(new Date())],
        [this.$t('message.dczh') + user.userName + ' -' + user.realName]
      ]
      const merges = [{ e: { r: 1, c: 0 }, s: { r: 2, c: 0 }}, { e: { r: 1, c: 1 }, s: { r: 2, c: 1 }}, { e: { r: 1, c: 2 }, s: { r: 2, c: 2 }}, { e: { r: 1, c: 3 }, s: { r: 2, c: 3 }}, { e: { r: 1, c: 4 }, s: { r: 1, c: 10 }}]
      const mergeList = this.mergeList
      const mergeIndexList = this.mergeIndexList
      for (var s = 0; s < mergeList.length; ++s) {
        if (mergeList[s] - mergeIndexList[s] > 1) {
          merges.push({ e: { r: Number(mergeIndexList[s]) + 3, c: 0 }, s: { r: Number(mergeList[s]) + 2, c: 0 }})
        }
      }
      // 创建工作簿
      var table_dom = this.$refs['tableRef'].$el
      const new_sheet = XLSX.utils.table_to_sheet(table_dom)
      const a = XLSX.utils.sheet_to_json(new_sheet, { header: 1 })
      aoa = aoa.concat(a).concat(bottom)
      const worksheet = XLSX.utils.json_to_sheet(aoa, { skipHeader: true })
      worksheet['!merges'] = merges
      const headerStyle = {
        font: {
          name: 'Arial'
        }
      }
      const contentStyle = {
        font: {
          name: 'Arial'
        }
      }
      const headerRange = XLSX.utils.decode_range(worksheet['!ref'])
      for (let col = headerRange.s.c; col <= headerRange.e.c; col++) {
        const headerCell = XLSX.utils.encode_cell({ r: headerRange.s.r, c: col })
        if (worksheet[headerCell]) {
          worksheet[headerCell].s = headerStyle
        }
      }

      // 将内容样式应用到 worksheet 对象中的所有单元格
      const contentRange = XLSX.utils.decode_range(worksheet['!ref'])
      for (let row = contentRange.s.r + 1; row <= contentRange.e.r; row++) {
        for (let col = contentRange.s.c; col <= contentRange.e.c; col++) {
          const contentCell = XLSX.utils.encode_cell({ r: row, c: col })
          if (worksheet[contentCell]) {
            worksheet[contentCell].s = contentStyle
          }
        }
      }
      XLSX.utils.book_append_sheet(workbook, worksheet, 'sheet1')
      const wbout = XLSX_STYLE.write(workbook, { bookType: 'xlsx', type: 'binary' })
      const blob = new Blob([this.s2ab(wbout)], { type: 'application/octet-stream' })
      saveAs(blob, filename)
    },
    s2ab(s) {
      const buf = new ArrayBuffer(s.length)
      const view = new Uint8Array(buf)
      for (let i = 0; i < s.length; i++) {
        view[i] = s.charCodeAt(i) & 0xFF
      }
      return buf
    },
    // 清空筛选项
    clearFilters() {
      this.filters = {
        time: this.filters.time
      }
      this.getDataList()
    }
  }
}
</script>
<style scoped lang="scss">
.han1 {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.tabDate {
  display: flex;
  div {
    background-color: #F5F7FA;
    color:#111111;
    display: inline-block;
    padding: 0 20px;
    height: 36px;
    line-height: 36px;
    box-sizing: border-box;
    cursor: pointer;
    &:nth-of-type(2){
      border-left: 1px solid #DCDFE6;
      border-right: 1px solid #DCDFE6;
    }
    &.on {
      color: #fff;
      background-color: #435EBE;
    }
  }
}
#echarts {
  width: 100%;
  height: 500px;
}
</style>

